import axios from 'axios';
import { ElMessage } from 'element-plus';
import Cookies from 'js-cookie';
import router from '@/router';

const baseURL = 'http://localhost:8080/api';
// 创建axios实例
const service = axios.create({
  baseURL: baseURL,
  timeout: 10000
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = Cookies.get('Admin-Token');
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    // 判断响应码
    if (res.code !== 200) {
      ElMessage({
        message: res.message || '请求失败',
        type: 'error',
        duration: 5 * 1000
      });
      
      // 401: 未登录或token过期
      if (res.code === 401) {
        // 重新登录
        router.push('/login');
      }
      
      return Promise.reject(new Error(res.message || '请求失败'));
    } else {
      return res;
    }
  },
  error => {
    console.error('响应错误:', error);
    ElMessage({
      message: error.message || '请求失败',
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service; 
export const BASE_URL = baseURL;